//不同类型的任务类型，使用不同的图层
//不同的房屋类型，使用不同的图层
//
define([
    "UtilDir/util",
    "UtilDir/tool",
    "static/app/fwsjcj/taskmanage/censusStatisticsEcharts",
],function(Util,Tool,Echarts) {
    var statisticalanalysisMap;

    var statisticalanalysisQueryAjax;
    var statisticalanalysisDatas = [];
    var statisticalanalysisDataInterval;
///////////////////////////////////////////////////////////////////////////天地图工具箱功能

    var polygonStatisticalTool;//任务区域
    var StatisticalPolygonPoints = [];
    var statisticalPolygon;
    var statisticalPoints;
    var colors = ["blue", "red", "yellow", "DarkOrage", "Lime", "Teal", "Fuchsia", "Green", "Black", "SpringGreen"];

    var citys=[];
    var nocitys=[];
    var villagehouses=[];
    var villagePublichouses=[];

    var statisticalDatas = [];//选中的房屋

    var sysPath =  getServer() + "/static/app/fwsjcj";
    var censusStatisticsFormHtml = sysPath + "/taskmanage/views/censusStatisticsForm.html";

    var getZwController = function(){
        return getServer() + "/fw/taskForm";
    };

//初始化
    function statisticalanalysisInitAll() {
        //初始化天地图及切换地图事件
        statisticalanalysisMap = initTMap(statisticalanalysisMap, 'statisticalanalysis-map', "#statisticalanalysis");
        if (statisticalanalysisMap != null) {//初始化地图成功
            clearStatisticalPolygon();
            initStatisticalMapDisplay();
            //初始化事件
            statisticalanalysisInitEvent();
            //添加浏览器的窗口调整地图页面大小事件
            initStatisticalDivZindex("#statisticalanalysis");
            //禁用浏览器右键菜单
            initTMapContextMenu();
            //获取基本数据
            getBaseDatas();
            //显示图例
            displayLegend();

            TEvent.addListener(statisticalanalysisMap,"moveend",displayRoundsstatisticalDatas);
            TEvent.addListener(statisticalanalysisMap,"zoomend",displayRoundsstatisticalDatas);
        } else {
            //地图初始化失败
            initAlert("#statisticalanalysis", "地图初始化失败", false);
        }
    }

    function getBaseDatas() {
        citys=[];
        citys.length=0;
        nocitys=[];
        nocitys.length=0;
        villagehouses=[];
        villagehouses.length=0;
        villagePublichouses=[];
        villagePublichouses.length=0;
        getFWDatas("0");// 城镇住宅
        getFWDatas("1");// 城镇非住宅
        getFWDatas("2");// 农村住房
        getFWDatas("3");// 农村公共建筑
    }

    var getFWDatas = function(type){
        $.ajax({
            url: getZwController() + "/findByType",
            data: {
                type: type
            },
            type: "get",
            success: function (data) {
                for (var i = 0; i < data.length; i++) {
                    var res = data[i];
                    if(type=="0") {
                        var city = new fwsjcjFWDetailinfos(res.fwId,type,res.bulidingLongitude,res.bulidingLatitude,res.buildingName,res.buildingTime,
                            res.structureType,res.housePurpose,res.buildingUpNum,res.presonNum,res.nowFortificationIntensity,res.result,res.spType,res.bulidingType);
                        citys.push(city);
                    }else if(type=="1"){
                        var nocity = new fwsjcjFWDetailinfos(res.fwId,type,res.bulidingLongitude,res.bulidingLatitude,res.buildingName,res.buildingTime,
                            res.structureType,res.housePurpose,res.buildingUpNum,"无",res.nowFortificationIntensity,res.result,res.spType,res.bulidingType);
                        nocitys.push(nocity);
                    }else if(type=="2"){
                        var villagehouse = new fwsjcjFWDetailinfos(res.fwId,type,res.bulidingLongitude,res.bulidingLatitude,res.buildingName,res.buildingTime,
                            res.structureType,"无",res.buildingLayerNum,res.presonNum,"无",res.result,res.spType,res.bulidingType);
                        villagehouses.push(villagehouse);
                    }else {
                        var villagePublichouse = new fwsjcjFWDetailinfos(res.fwId,type,res.bulidingLongitude,res.bulidingLatitude,res.buildingName,res.buildingTime,
                            res.structureType,res.housePurpose,res.buildingUpNum,res.presonNum,res.nowFortificationIntensity,res.result,res.spType,res.bulidingType);
                        villagePublichouses.push(villagePublichouse);
                    }
                }
            }
        });
    }

    function displayLegend() {
        $("#statisticalanalysis-fwlegend").show();
    }

    function initStatisticalMapDisplay() {
        statisticalanalysisMap.clearOverLays();
    }

//禁用浏览器右键菜单
    function initTMapContextMenu() {
        //禁用浏览器右键菜单
        document.oncontextmenu = function () {
            return false;
        };
    }

//地图缩放到权限位置
    function statisticalanalysisZoomDefaultPosition() {
        clearStatisticalPolygon();
        //获取权限区域选择列表
        //var LonLat = [113.2, 25.4];
        var LonLat = [103.2, 34.4];
        //地图缩放级别
        var zoom = 4;
        statisticalanalysisMap.centerAndZoom(new TLngLat(LonLat[0], LonLat[1]), zoom);

        //设置主界面图标文字
        initSetZoomDefaultPosition(true, "#statisticalanalysis");
    }

    function initSetZoomDefaultPosition(bool, str) {
        if (bool) {//返回主界面
            //设置主界面图标文字
            $(str + "-ZoomDefaultPosition img").attr("src", "/static/app/fwsjcj/taskmanage/image/home-r.png");
            $(str + "-ZoomDefaultPosition span").css("color", "#00a7ff");
        } else {
            //设置主界面图标文字
            $(str + "-ZoomDefaultPosition img").attr("src", "/static/app/fwsjcj/taskmanage/image/home.png");
            $(str + "-ZoomDefaultPosition span").css("color", "#fff");
        }
    }

//初始化DIV层叠顺序，设置Div位置居中
    function initStatisticalDivZindex(str) {
        if ($(str + "-mapDiv").offset() != undefined) {//有地图页面信息
            var bodyWidth = window.innerWidth - 15;//1920px
            var mapTop = $(str + "-mapDiv").offset().top;//142px
            var mapHeight = window.innerHeight - 40;//796px
            var mapWidth = bodyWidth;//1469px
            //设置地图宽度
            $(str + "-mapDiv").css("width", mapWidth + "px");
            //设置地图高度
            $(str + "-mapDiv").css("height", mapHeight + "px");
            //设置地图宽度
            $(str + "-map").css("width", mapWidth + "px");
            //设置地图高度
            $(str + "-map").css("height", mapHeight + "px");

            //设置鼠标经纬度位置Div位置
            $(str + "-mousemoveLngLatDiv").css("top", mapHeight - 50 + "px");

            //设置左侧控件栏位置
            $(str + "-setDivPosition").css("z-index", "1");

            //消息弹窗
            $(str + "-infosDiv").css("z-index", "3");
            $(str + "-stopQueryDiv").css("z-index", "3");
            //设置消息窗的位置向上居中
            $(str + "-infosDiv").css("left", mapWidth / 2 - $(str + "-infosDiv").outerWidth() / 2 + "px");
            $(str + "-infosDiv").css("top", "100px");
            //设置查询消息框的位置向上居中
            $(str + "-stopQueryDiv").css("left", mapWidth / 2 - $(str + "-stopQueryDiv").outerWidth() / 2 + "px");
            $(str + "-stopQueryDiv").css("top", "100px");

            //右键菜单
            $(str + "-contextMenuDiv").css("z-index", "4");
            //隐藏右键菜单
            $(str + "-contextMenuDiv").hide();
            statisticalanalysisMap.checkResize();
        }
    }

//设置DIV层叠顺序为最大，设置Div位置居中
    function initSetDivZindexMax(id) {
        var strArray = id.split("-");
        if (strArray.length == 2) {
            var str = strArray[0];
            //初始化DIV层叠顺序，设置Div位置居中
            initStatisticalDivZindex(str);
            //设置DIV的层叠顺序为最大
            $(id).css("z-index", "100");
        }
    }

////////////////////////////////////////////////////////////////////////////////定位工具
//获取鼠标经纬度
    function statisticalanalysisMousePositionCenter() {
        var str = "#statisticalanalysis";
        //获取鼠标经纬度——设置图标样式
        initMousePositionCenter(str);
        //鼠标经纬度
        var lng = $(str + "-MousePositionLon").val();
        var lat = $(str + "-MousePositionLat").val();
        if (lng != "" && lat != "") {
            //地图居中到定位图标位置
            statisticalanalysisMap.setCenter(new TLngLat(lng, lat));
            //定位图标
            var icon = new TIcon("/static/app/fwsjcj/taskmanage/image/marker2.png", new TSize(19, 27), {anchor: new TPixel(9, 27)});
            var marker = new TMarker(new TLngLat(lng, lat), {icon: icon});
            //图标文字
            var title = "经度：" + lng + "，纬度：" + lat;
            marker.setTitle(title);
            //添加定位图标到地图叠加层
            statisticalanalysisMap.addOverLay(marker);
            //添加到定位图标数组中
            statisticalanalysisPositionMarkers.push(marker);
            //注册标注点的点击事件
            TEvent.bind(marker, "click", marker, function () {
                var lnglat = this.getLngLat();
                //获取经纬度
                var fmapLonLat = new FMapLonLat({lnglat: lnglat});
                var lonlat = fmapLonLat.getLonLatByLngLat();
                //根据经纬度获取省市边界线
                statisticalanalysisLonLatGetRegion(lonlat);
                //地图居中缩放
                statisticalanalysisSetCenterZoom(lonlat, 18);
            });

        } else {
        }
    }

//获取鼠标经纬度——设置图标样式
    function initMousePositionCenter(str) {
        $(str + "-MousePositionDiv span").css("color", "#fff");
        $(str + "-dw_tj span").css("color", "#00a7ff");
        $(str + "-dw_tj img").attr("src", "/static/app/fwsjcj/taskmanage/image/dingwd-r.png");
        $(str + "-dw_qk img").attr("src", "/static/app/fwsjcj/taskmanage/image/qux.png");
    }


    function statisticalanalysisInitEvent() {
        //天地图事件
        $("#statisticalanalysis-ZoomDefaultPosition").unbind("click");
        $("#statisticalanalysis-ZoomDefaultPosition").click(function () {
            statisticalanalysisZoomDefaultPosition();
        });
        $("#statisticalanalysisDiv").unbind("click");
        $("#statisticalanalysisDiv").click(function () {
            creatRegion();
        });

        statisticalanalysisTMapEvent();
    }

    function clearStatisticalPolygon() {
        $("#statisticalanalysis-contextMenuDiv").hide();
        if (statisticalPolygon != null) {
            statisticalanalysisMap.removeOverLay(statisticalPolygon);
        }
        if (polygonStatisticalTool != null) {
            polygonStatisticalTool.clear();
            polygonStatisticalTool.close();
        }
    }

    function creatRegion() {
        clearStatisticalPolygon();
        if ($("#statisticalanalysisDiv img").attr("title") == "圈选统计") {
            $("#statisticalanalysisDiv img").attr("title", "取消统计");
            $("#statisticalanalysisDiv").children("span").html("取消统计");
            var index = Math.floor(Math.random() * 10);
            var color = colors[index];
            var config = {
                strokeColor: color, //折线颜色
                fillColor: "#FFFFFF",    //填充颜色。当参数为空时，折线覆盖物将没有填充效果
                strokeWeight: "3px", //折线的宽度，以像素为单位
                strokeOpacity: 1,  //折线的透明度，取值范围0 - 1
                fillOpacity: 0.2,        //填充的透明度，取值范围0 - 1
                showLabel: false             //是否显示页面，默认为true.
            };
            //创建任务工具对象
            polygonStatisticalTool = new TPolygonTool(statisticalanalysisMap, config);
            polygonStatisticalTool.setTips("单击鼠标左键绘制圈选区域点，双击完成绘制圈选区域");
            //注册测面工具绘制完成后的事件
            TEvent.addListener(polygonStatisticalTool, "draw", onDrawHZPolygon);
            polygonStatisticalTool.open();

            //添加多边形
            function onDrawHZPolygon(bounds, line) {
                StatisticalPolygonPoints.length = 0;
                polygonStatisticalTool.clear();
                statisticalPolygon = new TPolygon(bounds, {
                    strokeColor: "red",
                    strokeWeight: 3,
                    strokeOpacity: 1,
                    fillOpacity: 0.2
                });
                statisticalanalysisMap.addOverLay(statisticalPolygon);//添加多边形

                var points = lnglatdataswitch(statisticalPolygon.getLngLats());
                statisticalPoints=points;
                polygonStatisticalTool.close();

                statisticalDatas=[];
                statisticalDatas.length=0;

                for (var i = 0; i < citys.length; i++) {
                    var info = citys[i];
                    if(initPointInsidePolygon(points,info.point)) {
                        statisticalDatas.push(info);
                    }
                }
                for (var i = 0; i < nocitys.length; i++) {
                    var info = nocitys[i];
                    if(initPointInsidePolygon(points,info.point)) {
                        statisticalDatas.push(info);
                    }
                }
                for (var i = 0; i < villagehouses.length; i++) {
                    var info = villagehouses[i];
                    if(initPointInsidePolygon(points,info.point)) {
                        statisticalDatas.push(info);
                    }
                }
                for (var i = 0; i < villagePublichouses.length; i++) {
                    var info = villagePublichouses[i];
                    if(initPointInsidePolygon(points,info.point)) {
                        statisticalDatas.push(info);
                    }
                }

                displayRoundsstatisticalDatas();

               /* for (var i = 0; i < statisticalDatas.length; i++) {
                    var info = statisticalDatas[i];
                    var icon = initTMapGetIconByType(info.buildtype, info.sptype);
                    initTMapAddMarkLabelArray(statisticalanalysisMap, info, info.point, info.name, icon);
                }*/
                console.log(statisticalDatas);
            }
        }else{
            $("#statisticalanalysisDiv img").attr("title", "圈选统计");
            $("#statisticalanalysisDiv").children("span").html("圈选统计");
            statisticalanalysisMap.clearOverLays();
        }
    }

    function displayRoundsstatisticalDatas(){
        var zoom=statisticalanalysisMap.getZoom();
        var bounds = statisticalanalysisMap.getBounds();
        var minlon=bounds.XminNTU;
        var maxlon=bounds.XmaxNTU;
        var minlat=bounds.YminNTU;
        var maxlat=bounds.YmaxNTU;
        var displayDatas=[];
        var theSuitableDatas=[];
        for(var i=0;i<statisticalDatas.length;i++){
            var lon = statisticalDatas[i].lon;
            var lat = statisticalDatas[i].lat;
            if (judgeThePointInRectangle(lon, lat, minlon,maxlon, minlat,maxlat)) {
                theSuitableDatas.push(statisticalDatas[i]);
            }
        }
        if(theSuitableDatas.length>0){
            var count=100000;
            if(zoom<=5){
                count=1;
            }else if(zoom>5&&zoom<=6){
                count=3;
            }else if(zoom>6&&zoom<=7){
                count=5;
            }else if(zoom>7&&zoom<=8){
                count=10;
            }else if(zoom>8&&zoom<=9){
                count=15;
            }else if(zoom>9&&zoom<=10){
                count=20;
            }else if(zoom>10&&zoom<=12){
                count=30;
            }else if(zoom>10&&zoom<=12){
                count=45;
            }else if(zoom>12&&zoom<=14){
                count=60;
            }else if(zoom>14&&zoom<=16){
                count=80;
            }
            if(theSuitableDatas.length>count){
                for(var i=0;i<count;i++){
                    displayDatas.push(theSuitableDatas[i]);
                }
            }else{
                displayDatas=theSuitableDatas;
            }
            clearStatisticalFWDatas(statisticalanalysisMap);
            for (var i = 0; i < displayDatas.length; i++) {
                var info = displayDatas[i];
                var icon = initTMapGetIconByType(info.buildtype, info.sptype);
                initTMapAddMarkLabelArray(statisticalanalysisMap, info, info.point, info.name, icon);
            }
        }

    }

    function judgeThePointInRectangle(lon,lat,minlon,maxlon,minlat,maxlat){
        if(lon>=minlon&&lon<=maxlon&&lat>=minlat&&lat<=maxlat){
            return true;
        }
        return false;
    }



//天地图事件
    function statisticalanalysisTMapEvent() {
        //地图事件
        statisticalanalysisMap = initTMapEvent("#statisticalanalysis", statisticalanalysisMap);

        //地图鼠标点击事件
        TEvent.addListener(statisticalanalysisMap, "click", function (p, btn) {
            //将像素坐标转换成经纬度坐标
            var lnglat = statisticalanalysisMap.fromContainerPixelToLngLat(p);
            var Lon = lnglat.getLng();
            var Lat = lnglat.getLat();
            $("#statisticalanalysis-contextMenuDiv").hide();
            if (btn == 1) {//鼠标左键
                //获取鼠标位置的经纬度
                $("#statisticalanalysis-MousePositionLon").val(Lon);
                $("#statisticalanalysis-MousePositionLat").val(Lat);
            } else if (btn == 2) {
                var hitPoint = [];
                hitPoint[0] = Lon;
                hitPoint[1] = Lat;
                if (statisticalPoints != null && statisticalPoints.length > 2) {
                    if (initPointInsidePolygon(statisticalPoints, hitPoint)) {
                        initShowContextMenu("#statisticalanalysis", 1, p[0], p[1]);
                        statisticalCreateContextMenu();
                        return;
                    }
                }
            }
        });
    }

    function statisticalCreateContextMenu() {
        //设置右键菜单点击事件
        $("#statisticalanalysis-ContextMenuLi").off("click");
        $("#statisticalanalysis-ContextMenuLi").on("click", function () {
            if (statisticalDatas != null && statisticalDatas.length > 0) {
                $("#statisticalanalysis-contextMenuDiv").hide();
                _viewCensusStatisticsInfo(statisticalDatas);
            }else{
                $("#statisticalanalysis-contextMenuDiv").hide();
                Util.alert("所选区域没有房屋数据。");
            }

        });
    }

    window._viewCensusStatisticsInfo = function(fwDatas) {
        var slidebar = Util.slidebar({
            url: censusStatisticsFormHtml,
            width: "450px",
            cache: false,
            close : true,

            afterOpen: function () {
                selectRadio();
                $("#circlefwNum").val(statisticalDatas.length);
                $('.nav-map.nav-tabs').hide();
            },
            afterLoad: function () {
                //Tool.deserialize("censusStatisticsForm", JSON.stringify(fwDatas));

                $("#r1").on("click", function () {
                    selectRadio();
                });
                $("#r2").on("click", function () {
                    selectRadio();
                });
                $("#r3").on("click", function () {
                    selectRadio();
                });
                $("#r4").on("click", function () {
                    selectRadio();
                });
                $("#r5").on("click", function () {
                    selectRadio();
                });
                $("#r6").on("click", function () {
                    selectRadio();
                });
                $("#r7").on("click", function () {
                    selectRadio();
                });
            }
        });
    };

    function hideUnusedDiv(){
        $("#mapageBuildState").hide();
        $("#mapstructTypeState").hide();
        $("#mappresonNumState").hide();
        $("#mapearthquakeState").hide();
        $("#mapHousepurposeState").hide();
        $("#mapearthquakeSituationState").hide();
        $("#circlepersonNumDiv").hide();
        $("#circlefwLayerNumDiv").hide();
    }

    window.selectRadio = function() {
        var rd=document.getElementsByName('rdCensusStatistics');
        hideUnusedDiv();
        if(rd[0].checked)
        {
            $("#mapageBuildState").show();
            createAgeBuildEcharts();
            document.getElementById("mapageBuildlab").click();
        }
        if(rd[1].checked)
        {
            $("#circlepersonNumDiv").show();
            $("#circlepersonNum").val(getcircleFWpresonNum());
        }
        if(rd[2].checked)
        {
            $("#mapstructTypeState").show();
            createStructTypeEcharts();
            document.getElementById("mapstructTypelab").click();
        }
        if(rd[3].checked)
        {
            $("#mapearthquakeState").show();
            createNowfortificationintensityEcharts();
            document.getElementById("mapearthquakelab").click();
        }
        if(rd[4].checked)
        {
            $("#mapHousepurposeState").show();
            createHousepurposeEcharts();
            document.getElementById("mapHousepurposelab").click();
        }
        if(rd[5].checked)
        {
            $("#mapearthquakeSituationState").show();
            createResultEcharts();
            document.getElementById("mapearthquakeSituationlab").click();
        }
        if(rd[6].checked)
        {
            $("#circlefwLayerNumDiv").show();
            $("#circlefwLayerNum").val(getcircleFWLayersNum());
        }
    }

    function getcircleFWLayersNum(){
        var num=0;
        for(var i=0;i<statisticalDatas.length;i++){
            var data = statisticalDatas[i];
            if(data.buildingupnum!=""&&data.buildingupnum!="无"){
                var j = parseInt(data.buildingupnum);
                if(j>0) {
                    num += j;
                }
            }
        }
        return num;
    }

    function getcircleFWpresonNum(){
        var num=0;
        for(var i=0;i<statisticalDatas.length;i++){
            var data = statisticalDatas[i];
            if(data.presonnum!=""&&data.presonnum!="无"){
                var j = parseInt(data.presonnum);
                if(j>0) {
                    num += j;
                }
            }
        }
        return num;
    }

    var createHousepurposeEcharts = function(){
        Echarts.createPieEcharts({
            id:"mapHousepurpose",
            legenddata: ['中小学','幼儿园','医院','福利院','其它公共建筑','工业建筑','其它'],
            title: "建筑用途（非住宅）",
            subtitle: '栋数',
            series: [
                {
                    name: '栋数',
                    data: [
                        {value: getHousepurposeNum("中小学"), name: '中小学'},
                        {value: getHousepurposeNum("幼儿园"), name: '幼儿园'},
                        {value: getHousepurposeNum("医院"), name: '医院'},
                        {value: getHousepurposeNum("福利院"), name: '福利院'},
                        {value: getHousepurposeNum("其它公共建筑"), name: '其它公共建筑'},
                        {value: getHousepurposeNum("工业建筑"), name: '工业建筑'},
                        {value: getHousepurposeNum("其它"), name: '其它'}
                    ]
                }
            ]
        });
        Echarts.resizeEcharts('mapHousepurpose');
    }

    function getHousepurposeNum(type) {
        var num=0;
        for(var i=0;i<statisticalDatas.length;i++){
            var data = statisticalDatas[i];
            if(data.housepurpose==type){
                num++;
            }
        }
        return num;
    }

    var createResultEcharts = function(){
        Echarts.createPieEcharts({
            id:"mapearthquakeSituation",
            legenddata: ['未抗震设防','抗震设防能力不足','基本符合抗震设防要求','疑似存在安全隐患'],
            title: "抗震设防初步结论",
            subtitle: '栋数',
            series: [
                {
                    name: '栋数',
                    data: [
                        {value: getResultNum("未抗震设防"), name: '未抗震设防'},
                        {value: getResultNum("抗震设防能力不足"), name: '抗震设防能力不足'},
                        {value: getResultNum("基本符合抗震设防要求"), name: '基本符合抗震设防要求'},
                        {value: getResultNum("疑似存在安全隐患"), name: '疑似存在安全隐患'}
                    ]
                }
            ]
        });
        Echarts.resizeEcharts('mapearthquakeSituation');
    }

    function getResultNum(type) {
        var num=0;
        for(var i=0;i<statisticalDatas.length;i++){
            var data = statisticalDatas[i];
            if(data.result!=null&&data.result!=""&&data.result.indexOf(type)!=-1){
                num++;
            }
        }
        return num;
    }

    var createNowfortificationintensityEcharts = function(){
        Echarts.createPieEcharts({
            id:"mapearthquake",
            legenddata: ['0（不设防）','6（VI度设防）','7（VII度设防）','8（VIII度设防）','9（IX度设防）'],
            title: "现抗震设防烈度",
            subtitle: '栋数',
            series: [
                {
                    name: '栋数',
                    data: [
                        {value: getNowfortificationintensityNum("未设防"), name: '0（不设防）'},
                        {value: getNowfortificationintensityNum("6"), name: '6（VI度设防）'},
                        {value: getNowfortificationintensityNum("7"), name: '7（VII度设防）'},
                        {value: getNowfortificationintensityNum("8"), name: '8（VIII度设防）'},
                        {value: getNowfortificationintensityNum("9"), name: '9（IX度设防）'}
                    ]
                }
            ]
        });
        Echarts.resizeEcharts('mapearthquake');
    }

    function getNowfortificationintensityNum(type) {
        var num=0;
        for(var i=0;i<statisticalDatas.length;i++){
            var data = statisticalDatas[i];
            if(data.nowfortificationintensity!=null&&data.nowfortificationintensity!=""&&data.nowfortificationintensity.indexOf(type)!=-1){
                num++;
            }
        }
        return num;
    }

    var createPresonNumEcharts = function(){
        Echarts.createPieEcharts({
            id:"mappresonNum",
            legenddata: ['0-50','51-100','101-200','201-500','501-1000','1000以上'],
            title: "人口或户数",
            subtitle: '栋数',
            series: [
                {
                    name: '栋数',
                    data: [
                        {value: getFWpresonNum(0,50), name: '0-50'},
                        {value: getFWpresonNum(51,100), name: '51-100'},
                        {value: getFWpresonNum(101,200), name: '101-200'},
                        {value: getFWpresonNum(201,500), name: '201-500'},
                        {value: getFWpresonNum(501,1000), name: '501-1000'},
                        {value: getFWpresonNum(1001,1001), name: '1000以上'}
                    ]
                }
            ]
        });
        Echarts.resizeEcharts('mappresonNum');
    }

    function getFWpresonNum(min,max) {
        var num=0;
        for(var i=0;i<statisticalDatas.length;i++){
            var data = statisticalDatas[i];
            if(data.presonnum!=""&&data.presonnum!="无"){
                var j = parseInt(data.presonnum);
                if(min!=max) {
                    if (j >= min && j <= max) {
                        num++;
                    }
                }else{
                    if(j>=min){
                        num++;
                    }
                }
            }else{
                if(min==0){
                    num++;
                }
            }
        }
        return num;
    }

    var createStructTypeEcharts = function(){
        Echarts.createPieEcharts({
            id:"mapstructType",
            legenddata: ['砖混','底层混凝土柱-上部砖混','钢筋混凝土','砖木','钢结构','木结构','其它'],
            title: "结构类型",
            subtitle: '栋数',
            series: [
                {
                    name: '栋数',
                    data: [
                        {value: getFWstructTypeNum("砖混"), name: '砖混'},
                        {value: getFWstructTypeNum("底层混凝土柱-上部砖混"), name: '底层混凝土柱-上部砖混'},
                        {value: getFWstructTypeNum("钢筋混凝土"), name: '钢筋混凝土'},
                        {value: getFWstructTypeNum("砖木"), name: '砖木'},
                        {value: getFWstructTypeNum("钢结构"), name: '钢结构'},
                        {value: getFWstructTypeNum("木结构"), name: '木结构'},
                        {value: getFWstructTypeNum("其它"), name: '其它'}
                    ]
                }
            ]
        });
        Echarts.resizeEcharts('mapstructType');
    }

    function getFWstructTypeNum(type) {
        var num=0;
        for(var i=0;i<statisticalDatas.length;i++){
            var data = statisticalDatas[i];
            if(data.structuretype==type){
                num++;
            }
        }
        return num;
    }

    var createAgeBuildEcharts = function(){
        Echarts.createPieEcharts({
            id:"mapageBuildings",
            legenddata: ['70s以前','70s','80s','90s','00s','10s'],
            title: "建造时间",
            subtitle: '栋数',
            series: [
                {
                    name: '栋数',
                    data: [
                        {value: getFWAgeNum("70s以前"), name: '70s以前'},
                        {value: getFWAgeNum("70s"), name: '70s'},
                        {value: getFWAgeNum("80s"), name: '80s'},
                        {value: getFWAgeNum("90s"), name: '90s'},
                        {value: getFWAgeNum("00s"), name: '00s'},
                        {value: getFWAgeNum("10s"), name: '10s'}
                    ]
                }
            ]
        });
        Echarts.resizeEcharts('mapageBuildings');
    }
    
    function getFWAgeNum(years) {
        var num=0;
        for(var i=0;i<statisticalDatas.length;i++){
            var data = statisticalDatas[i];
            if(data.buildingtime==years){
                 num++;
            }
        }
        return num;
    }

    function initTMapEvent(str, map) {
        //str:#statistical-analysis
        if (map != null) {
            //地图当前鼠标位置
            //注册鼠标在地图上的滑动事件
            TEvent.addListener(map, "mousemove", function (p) {
                //将像素坐标转换成经纬度坐标
                var lnglat = map.fromContainerPixelToLngLat(p);
                $(str + "-mousemoveLngLatDiv").html("鼠标位置经纬度：" + lnglat.getLng() + "," + lnglat.getLat());
            });
            //地图拖拽事件
            TEvent.addListener(map, "mousedrag", function () {
                //设置主界面图标文字
                initSetZoomDefaultPosition(false, str);
                $(str + "-contextMenuDiv").hide();
            });

            //地图缩放事件
            TEvent.addListener(map, "zoom", function () {
                //设置主界面图标文字
                initSetZoomDefaultPosition(false, str);
                var zoom = map.getZoom();
                if (str == "#statisticalanalysis") {

                    if (zoom > 4) {
                    } else if (zoom == 4) {
                        //地图缩放到权限位置
                        //statisticalanalysisZoomDefaultPosition();
                    }

                }

            });
        }

        return map;
    }

    function initSetSwitchMap(str, map) {
        clearStatisticalPolygon();
        var strSwitchMap = str + "-switchMap";
        $(strSwitchMap).children("span").html("卫星图");
        $(strSwitchMap).children("img").attr("title", "切换卫星地图");
        $(strSwitchMap).children("img").attr("src", "/static/app/fwsjcj/taskmanage/image/weixing-b.png");
        $(strSwitchMap).children("img").css("margin-left", "5px");
        //显示街道图
        map.setMapType(TMAP_NORMAL_MAP);
        //切换卫星图和街道图事件
        $(strSwitchMap).click(function () {
            //切换地图功能控件
            if ($(strSwitchMap).children("img").attr("src") == "/static/app/fwsjcj/taskmanage/image/jiedao-b.png") {
                $(strSwitchMap).children("span").html("卫星图");
                $(strSwitchMap).children("img").attr("title", "切换卫星地图");
                $(strSwitchMap).children("img").attr("src", "/static/app/fwsjcj/taskmanage/image/weixing-b.png");
                $(strSwitchMap).children("img").css("margin-left", "5px");
                //显示街道图
                map.setMapType(TMAP_NORMAL_MAP);
            } else if ($(strSwitchMap).children("img").attr("src") == "/static/app/fwsjcj/taskmanage/image/weixing-b.png") {
                $(strSwitchMap).children("span").html("街道图");
                $(strSwitchMap).children("img").attr("title", "切换街道地图");
                $(strSwitchMap).children("img").attr("src", "/static/app/fwsjcj/taskmanage/image/jiedao-b.png");
                //显示卫星图
                map.setMapType(TMAP_HYBRID_MAP);//卫星图（有标注）
            }
        });
    }

//初始化卫星和街道地图及切换地图事件
    function initTMap(map, strMap, str) {
        try {
            //判断是否连接上地图API
            var temp = TLocalSearch();
            var config = {
                projection: "EPSG:4326"
            }
            //初始化地图对象
            map=new TMap(strMap,config);
            //初始化地图
            //map = new TMap(strMap);
            //清空地图
            map.clearOverLays();
            //地图中心坐标--全国
            //var LonLat  = [109.2, 34.4];
            //var LonLat = [113.2, 25.4];
            var LonLat = [103.2, 34.4];
            //地图缩放级别
            var zoom = 4;
            map.centerAndZoom(new TLngLat(LonLat[0], LonLat[1]), zoom);
            map.enableDoubleClickZoom();
            map.enableHandleMouseScroll();

            //创建比例尺控件对象
            var scale = new TScaleControl();
            //添加比例尺控件
            map.addControl(scale);

            //鹰眼
            var configOverView = {
                anchor: "TMAP_ANCHOR_BOTTOM_RIGHT",	//设置鹰眼位置,"TMAP_ANCHOR_TOP_LEFT"表示左上，"TMAP_ANCHOR_TOP_RIGHT"表示右上，"TMAP_ANCHOR_BOTTOM_LEFT"表示左下，"TMAP_ANCHOR_BOTTOM_RIGHT"表示右下，"TMAP_ANCHOR_LEFT"表示左边，"TMAP_ANCHOR_TOP"表示上边，"TMAP_ANCHOR_RIGHT"表示右边，"TMAP_ANCHOR_BOTTOM"表示下边，"TMAP_ANCHOR_OFFSET"表示自定义位置,默认值为"TMAP_ANCHOR_BOTTOM_RIGHT"
                size: new TSize(180, 120),			//鹰眼显示的大小
                isOpen: true						//鹰眼是否打开，true表示打开，false表示关闭，默认为关闭
            };
            //创建鹰眼控件对象
            var overviewMap = new TOverviewMapControl(configOverView);
            //添加鹰眼控件
            map.addControl(overviewMap);

            //地图缩放平移控件
            var config = {
                type: "TMAP_NAVIGATION_CONTROL_ZOOM",	//缩放平移的显示类型
                anchor: "TMAP_ANCHOR_TOP_RIGHT",			//缩放平移控件显示的位置
                offset: [0, 0],							//缩放平移控件的偏移值
                showZoomInfo: false						//是否显示级别提示信息，true表示显示，false表示隐藏。
            };
            //创建缩放平移控件对象
            var navigationControl = new TNavigationControl(config);
            //添加缩放平移控件
            map.addControl(navigationControl);

            //设置地图显示级别
            map.setZoomLevels([4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]);

            //切换卫星和街道图
            initSetSwitchMap(str, map);
            //设置控件显示
            $(str + "-setDivPosition").show();//显示工具条控件
            $(str + "-mousemoveLngLatDiv").show();//显示鼠标经纬度信息栏
            $(str + "-tabControlDiv").show();//显示侧边栏

            //全屏设置功能
            //initTMapSetFullScreen();

        } catch (e) {
            map = null;
        }

        return map;
    }

//信息窗样式设置
    function initAlert(str, data, bool) {
        if (data == "没有选择区域" || data == "初始化成功！" || data == "初始化失败！" || data == "地图初始化失败！" || data == "查询成功！" || data == "查询失败！" || data == "无查询结果！" || data == "处理成功！" || data == "处理失败！" || data == "设置成功！" || data == "设置失败！" || data == "保存成功！" || data == "删除成功！" || data == "清空成功！" || data == "线路规划成功！") {
            $(str + "-stopQueryDiv").hide();
        }
        //设置DIV层叠顺序为最大
        initSetDivZindexMax(str + "-infosDiv");
        //消息提示图标
        if (bool) {//成功
            $(str + "-infosDiv img").attr("src", "/static/app/fwsjcj/taskmanage/image/succes.png");
        } else {//失败
            $(str + "-infosDiv img").attr("src", "/static/app/fwsjcj/taskmanage/image/error.png");
        }
        $(str + "-infosDiv img").css("top", "75px");
        $(str + "-infosDiv img").css("left", "60px");
        //设置信息框显示文字
        $(str + "-infosDiv p").html(data);
        $(str + "-infosDiv").show();
        //消息提示3秒后自动关闭
        setTimeout(function () {
            $(str + "-infosDiv").hide();
        }, 1000);
    }

    return {
        statisticalanalysisInitAll: statisticalanalysisInitAll
    };
});